import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {InfoCircleOutlined} from "@ant-design/icons";
import { Input, Modal, InputNumber, Upload, Button, Icon, Select, Radio,Tooltip,Table } from 'antd';
import { formatMessage, FormattedMessage} from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState } from 'react';
import styles from '../style.less'

// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';

// 常量
const { TextArea } = Input;
const FormItem = Form.Item;
const Option = Select;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
  dataList: any
  onSubmit: (fieldsValue: any) => any;
  onCancel: () => void;
}

// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { dataModalVisible, form, onSubmit: handleSubmit, onCancel,
    common, isUpdate,dataFormValues,dataList } = props;

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');

  const [continent,setContinent] = useState<any>('');
  const [nation,setNation] = useState<any>('');

  //提交表单
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      
      // 如果是更新
      if(isUpdate){
        fieldsValue.id = dataFormValues.id;
      }
      //查重
      var name = getNameById(fieldsValue.mapId,common.mapServiceOption);
      let itemJson = {
        mapId: fieldsValue.mapId,
        appId: fieldsValue.appId,
        appKey: fieldsValue.appKey,
      }
      
      console.log("submit fields ", fieldsValue)
      var submitValue = {
        item_key: `map_${fieldsValue.mapId}`,
        item_json: JSON.stringify(itemJson),
        map_plugin: fieldsValue.plugin_unikey,
        map_id: fieldsValue.mapId,
        map_name: name,
      }
      // 如果更新成功之后，重置表单
      handleSubmit(submitValue);

    });
  };

  //根据id获取name
  const getNameById = (id:any,options:any) => {
    var name = "";
    if(id && options && options.length > 0){
      options.map((item:any,index:any)=>{
        if(item.key == id){
          name = item.text;
        }
      })
    }
    return name
  }

  //地区去重校验
  const cancelRepet = (con:any,nation:any)=>{
    var isRepet = false;
    if(dataList.length > 0){
      dataList.map((item:any,index:any)=>{
        if(con == item.continent && nation == item.nation){
          isRepet = true;
        }
      })

    }
    return isRepet
  }

  // 设置上传文件值
  const setUploadFile = (fileList:any) => {
    setUploadChanged(true)
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if(fileArr.length > 0){
      setPicture(fileArr)
      setPreviewImg(fileArr[0].file_url)
    }else if(fileArr.length === 0){
      console.log('set picture []')
      setPicture([])
    }
  }

  // 初始化变量
  const token = BdHelper.getBdToken()

  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(dataFormValues.file_url)

  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)

  // 弹出框
  // @ts-ignore
  return <Modal
    destroyOnClose
    title={'新增服务商'}
    width={"40%"}
    visible={dataModalVisible}
    onOk={okHandle}
    onCancel={() => onCancel()}
  >

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: '服务商' })}>
      {form.getFieldDecorator('mapId', {
        initialValue: isUpdate ? dataFormValues?.mapId && (dataFormValues?.mapId).toString() : undefined,
        //  rules: [{ required: true, message: '请选择！',}],
      })(<Select disabled={isUpdate} placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
        {common.mapServiceOption && TsxHelper.buildNameSelectOption(common.mapServiceOption)}
      </Select>)}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: '关联插件' })}>
      {form.getFieldDecorator('plugin_unikey', {
        initialValue: isUpdate ? dataFormValues?.plugin_unikey && (dataFormValues?.plugin_unikey).toString() : undefined,
         rules: [{ required: true, message: '请选择！',}],
      })(<Select disabled={isUpdate} placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
        {common.mapOption && TsxHelper.buildNameSelectOption(common.mapOption)}
      </Select>)}
    </FormItem>

    <FormItem
    label={
      <span >
        <FormattedMessage id="App ID" />
        {/* <em className={styles.optional}>
          <Tooltip title={<FormattedMessage id="没有则留空" />}>
            <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
          </Tooltip>
        </em> */}
      </span>
    }
    style={{marginBottom:5}} labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
      {form.getFieldDecorator('appId', {
        initialValue: isUpdate ? dataFormValues?.appId : '',
      })(<Input  placeholder={''}/>)}
    </FormItem>

    <FormItem
    label={
      <span >
        <FormattedMessage id="App Key" />
      </span>
    }
    style={{marginBottom:5}} labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
      {form.getFieldDecorator('appKey', {
        initialValue: isUpdate ? dataFormValues?.appKey : '',
      })(<Input  placeholder={''}/>)}
    </FormItem>

    {/* <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} 
    label={
      <span>
        <FormattedMessage id="启用状态" />
      </span>
    }>
      {form.getFieldDecorator('isEnable', {
        initialValue: isUpdate ? dataFormValues?.isEnable : false,
        // rules: [{ required: true, message: '请选择！',}],
      })(<Radio.Group buttonStyle="solid">
          <Radio value={true}>启用</Radio>
          <Radio value={false}>不启用</Radio>
        </Radio.Group>
      )}
    </FormItem> */}

    {/* <FormItem
    label={
      <span >
        <FormattedMessage id="自定义参数" />
      </span>
    }
    style={{marginBottom:5}} labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
      {form.getFieldDecorator('custom_param', {
        initialValue: isUpdate ? dataFormValues?.custom_param : '',
      })(<Input  placeholder={''}/>)}
    </FormItem> */}

    
    
    {
      previewModelVisible && (
        <PreviewForm
          previewModelVisible={previewModelVisible}
          onVisibleModel={handlePreviewModalVisible}
          previewImg={previewImg}
        />
      )
    }
  </Modal>;
};

export default Form.create<DataFormProps>()(DataForm);
